<template>
  <el-container>
    <el-main>
      <el-form class="sa-m-b-16" label-width="90px">
        <el-form-item label="菜单名称">
          <el-input
            class="menu-name"
            v-model="menuData.detail.name"
            placeholder="当前菜单名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="menu-content sa-flex">
        <div class="menu-content-left">
          <div class="title">公众号菜单</div>
          <div class="left-bottom sa-flex">
            <div class="left-icon sa-flex">
              <sa-svg name="sa-menu-keyboard" size="20"></sa-svg>
            </div>
            <!-- 拖动组件 -->
            <draggable
              :list="menuData.left"
              class="sa-flex sa-flex-1"
              animation="100"
              item-key="event"
            >
              <template #item="{ element, index }">
                <div
                  class="draggable-item menu-item sa-flex sa-row-center cursor-pointer"
                  @click.stop="editMenu(index, null)"
                  :class="element.selected ? 'active' : ''"
                >
                  <span v-if="element.sub_button && element.sub_button.length > 0" class="sa-m-r-4"
                    >≡</span
                  >
                  <span class="sa-line-1">{{ element.name }}</span>
                  <div
                    v-if="element.sub_button"
                    class="menu-level2-body"
                    :class="element.show ? 'menu-level2-body-show' : ''"
                    :style="{
                      'border-bottom':
                        element.sub_button.length >= 5 ? '1px solid #E7E7EB' : 'none',
                    }"
                  >
                    <draggable :list="element.sub_button" animation="500" item-key="event">
                      <template #item="scope">
                        <div>
                          <div
                            class="menu-item sa-line-1"
                            @click.stop="editMenu(index, scope.index)"
                            :class="scope.element.selected ? 'active' : ''"
                            >{{ scope.element.name }}</div
                          >
                        </div>
                      </template>
                    </draggable>
                    <div
                      class="menu-item menu-level2-add cursor-pointer"
                      v-if="element.sub_button.length < 5"
                      @click.stop="addMenu(index, 2)"
                    >
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </template>
              <template #footer>
                <div
                  class="left-add sa-flex sa-row-center cursor-pointer"
                  v-if="menuData.left.length < 3"
                  @click.stop="addMenu(null, 1)"
                >
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </template>
            </draggable>
          </div>
          <div class="tip sa-m-t-8">可直接拖动菜单排序</div>
        </div>
        <div class="menu-content-right-tip sa-flex sa-row-center" v-if="!rightShow"
          >您尚未添加自定义菜单</div
        >
        <div class="menu-content-right" v-if="rightShow">
          <div class="sa-flex sa-row-between sa-m-b-38">
            <div class="title">菜单名称</div>
            <div class="delete" @click="deleteMenu">删除菜单</div>
          </div>
          <el-form :model="menuData.right" label-width="86px">
            <el-form-item :label="selectLevel == 2 ? '子菜单名称' : '菜单名称'" prop="name">
              <el-input v-model="menuData.right.name"></el-input>
              <div class="tip">菜单名称字数不多于4个汉字或8个字母</div>
            </el-form-item>
            <el-form-item
              v-if="
                (selectLevel == 1 &&
                  (!menuData.right.sub_button || menuData.right.sub_button.length == 0)) ||
                selectLevel == 2
              "
              :label="selectLevel == 2 ? '子页面内容' : '页面内容'"
            >
              <el-radio-group v-model="menuData.right.type" @change="onChangeType">
                <el-radio label="view">跳转网页</el-radio>
                <el-radio label="miniprogram">跳转小程序</el-radio>
                <el-radio label="click">回复素材</el-radio>
              </el-radio-group>
              <div class="tip">点击该菜单会跳到页面链接</div>
            </el-form-item>
            <template v-if="!menuData.right.sub_button || menuData.right.sub_button.length == 0">
              <template v-if="menuData.right.type == 'miniprogram'">
                <el-form-item label="AppId">
                  <el-input v-model="menuData.right.appid"></el-input>
                </el-form-item>
                <el-form-item label="小程序路径">
                  <el-input v-model="menuData.right.pagepath"></el-input>
                </el-form-item>
                <el-form-item style="margin-top: -20px">
                  <div class="tip" v-if="menuData.right.type == 'view'"
                    >点击该菜单会跳到页面链接</div
                  >
                  <div class="tip" v-if="menuData.right.type == 'miniprogram'"
                    >小程序路径不可用时跳转页面链接</div
                  >
                </el-form-item>
              </template>
              <template
                v-if="menuData.right.type == 'view' || menuData.right.type == 'miniprogram'"
              >
                <el-form-item label="页面链接">
                  <el-input v-model="menuData.right.url"></el-input>
                </el-form-item>
              </template>
              <!-- 回复素材 -->
              <template v-if="menuData.right.type == 'click'">
                <el-form-item label="消息类型">
                  <el-radio-group v-model="menuData.right.media_type" @change="onChangeMediaType">
                    <el-radio label="news">图文消息</el-radio>
                    <el-radio label="image">图片</el-radio>
                    <el-radio label="video">视频</el-radio>
                    <el-radio label="voice">语音</el-radio>
                    <el-radio label="text">文本</el-radio>
                    <el-radio label="link">链接</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="menuData.right.media_type" label="消息内容">
                  <el-select popper-class="material-select" v-model="menuData.right.media_id">
                    <el-option
                      v-for="item in contentOptions.data"
                      :key="item.media_id"
                      :label="item.title"
                      :value="item.media_id + ''"
                    >
                      <div class="sa-flex">
                        <sa-image
                          v-if="
                            item.type == 'news' ||
                            item.type == 'image' ||
                            item.type == 'video' ||
                            item.type == 'link'
                          "
                          :url="item.thumb_url"
                          size="30"
                        ></sa-image>
                        <div class="title sa-m-l-12 sa-line-1">
                          {{ item.title }}
                        </div>
                        <div class="media_id sa-line-1">
                          {{ item.media_id }}
                        </div>
                      </div>
                    </el-option>
                    <div class="material-select-pagination sa-flex">
                      <el-pagination
                        @size-change="changeSize($event, menuData.right.media_type)"
                        @current-change="changeCurrent($event, menuData.right.media_type)"
                        v-model:currentPage="contentOptions.page"
                        :page-sizes="[10, 20]"
                        :page-size="contentOptions.list_rows"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="contentOptions.total"
                        :pager-count="5"
                      ></el-pagination>
                    </div>
                  </el-select>
                  <!-- <material-select
                    v-model:value="menuData.right.media_id"
                    :type="menuData.right.type"
                    :media_type="menuData.right.media_type"
                  ></material-select> -->
                </el-form-item>
              </template>
            </template>
          </el-form>
        </div>
      </div>
    </el-main>
    <el-footer class="sa-footer--submit">
      <template v-if="modal.params.type == 'add'">
        <el-button
          v-auth="'wechat.admin.menu.add'"
          type="primary"
          plain
          :disabled="menuData.left.length == 0"
          @click="save"
          >保存</el-button
        >
        <el-button
          v-auth="['wechat.admin.menu.add', 'wechat.admin.menu.publish']"
          type="primary"
          :disabled="menuData.left.length == 0"
          @click="publish"
          >保存&发布</el-button
        >
      </template>
      <template v-if="modal.params.type == 'edit'">
        <el-button v-auth="'wechat.admin.menu.edit'" type="primary" plain @click="save"
          >更新</el-button
        >
        <el-button
          v-auth="['wechat.admin.menu.edit', 'wechat.admin.menu.publish']"
          type="primary"
          @click="publish"
          >更新&发布</el-button
        >
      </template>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { useModal } from '@/sheep/hooks';
  import wechat from '@/app/wechat/api';
  import draggable from 'vuedraggable';
  import materialSelect from '../material/select.js';
  import { cloneDeep } from 'lodash';

  const { contentOptions, getMaterialSelect, changeSize, changeCurrent } = materialSelect();

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  const menuData = reactive({
    detail: {
      name: '',
    },
    left: [],
    right: [],
  });
  const rightShow = ref(false);
  const selectLevel = ref();
  const selectedIndex1 = ref();
  const selectedIndex2 = ref();
  const view = ['name', 'type', 'url', 'sub_button'];
  const miniprogram = ['name', 'type', 'url', 'appid', 'pagepath', 'sub_button'];
  const click = ['name', 'type', 'media_type', 'media_id', 'sub_button'];
  const defaultSubButton = {
    name: '未命名',
    type: 'view',
    selected: true,
    show: true,
    url: '',
    appid: '',
    pagepath: '',
    sub_button: [],
    media_type: 'news',
    media_id: '',
  };
  async function getDetail() {
    const { error, data } = await wechat.admin.menu.detail(props.modal.params.id);
    if (error === 0) {
      menuData.detail = data;
      menuData.left = data.rules;
      initData();
    }
  }
  // 添加
  function addMenu(index, level) {
    //右侧显示
    rightShow.value = true;
    selectLevel.value = level;
    // 添加level2的数据
    if (index != null) {
      selectedIndex1.value = index;
      menuData.left.forEach((i) => {
        i.selected = false;
        if (i.sub_button) {
          i.sub_button.forEach((j) => {
            j.selected = false;
          });
        }
      });

      menuData.left[index].sub_button.push(cloneDeep(defaultSubButton));
      menuData.right = menuData.left[index].sub_button[menuData.left[index].sub_button.length - 1];
      selectedIndex2.value = menuData.left[index].sub_button.length - 1;
    } else {
      // 添加level1的数据
      // 所有的level1不显示
      menuData.left.forEach((i) => {
        i.selected = false;
        i.show = false;
      });
      menuData.left.push(cloneDeep(defaultSubButton));
      selectedIndex1.value = menuData.left.length - 1;
      menuData.right = menuData.left[menuData.left.length - 1];
    }
  }
  // 编辑
  function editMenu(index1, index2) {
    selectedIndex1.value = index1;
    selectedIndex2.value = index2;
    rightShow.value = true;
    menuData.left.forEach((i) => {
      i.selected = false;
      i.show = false;
      if (i.sub_button) {
        i.sub_button.forEach((j) => {
          j.selected = false;
        });
      }
    });
    menuData.left[index1].show = true;
    //选择1
    if (index2 == null) {
      selectLevel.value = 1;
      menuData.left[index1].selected = true;
      menuData.left[index1].show = true;
      menuData.right = menuData.left[index1];
    } else {
      selectLevel.value = 2;
      menuData.left[index1].sub_button[index2].selected = true;
      menuData.right = menuData.left[index1].sub_button[index2];
    }
    if (menuData.right.media_type) {
      // getoptions();
    }
  }
  // 删除
  function deleteMenu() {
    if (selectedIndex2.value != null) {
      menuData.left[selectedIndex1.value].sub_button.splice(selectedIndex2.value, 1);
      if (menuData.left[selectedIndex1.value].sub_button.length > 0) {
        if (selectedIndex2.value == 0) {
          menuData.left[selectedIndex1.value].sub_button[0].selected = true;
          menuData.right = menuData[selectedIndex1.value].sub_button[0];
        } else {
          menuData.left[selectedIndex1.value].sub_button[selectedIndex2.value - 1].selected = true;
          menuData.right = menuData.left[selectedIndex1.value].sub_button[selectedIndex2.value - 1];
          selectedIndex2.value--;
        }
      } else {
        menuData.right = {};
        rightShow.value = false;
      }
    } else {
      menuData.left.splice(selectedIndex1.value, 1);
      if (menuData.left.length > 0) {
        if (selectedIndex1.value == 0) {
          menuData.left[0].selected = true;
          menuData.left[0].show = true;
          menuData.right = menuData.left[0];
        } else {
          menuData.left[selectedIndex1.value - 1].selected = true;
          menuData.left[selectedIndex1.value - 1].show = true;
          menuData.right = menuData.left[selectedIndex1.value - 1];
          selectedIndex1.value--;
        }
      } else {
        menuData.right = {};
        rightShow.value = false;
      }
    }
  }

  function onChangeType() {
    if (menuData.right.type == 'click') {
      getMaterialSelect(menuData.right.media_type);
    }
  }
  function onChangeMediaType() {
    menuData.right.media_id = '';
  }
  watch(
    () => menuData.right.media_type,
    () => {
      getMaterialSelect(menuData.right.media_type);
    },
  );

  // 初始化数据
  function initData() {
    menuData.left.forEach((d) => {
      loopData(d);
    });
    function loopData(d) {
      for (var key in defaultSubButton) {
        if (!d[key]) {
          d[key] = cloneDeep(defaultSubButton)[key];
        }
        d.selected = false;
        d.show = false;
      }
      if (d.type == 'click') {
        d.media_type = d.key?.split('|')[0];
        d.media_id = d.key?.split('|')[1];
      }
      if (d.sub_button && d.sub_button.length > 0) {
        d.sub_button.forEach((s) => {
          loopData(s);
        });
      }
    }
  }
  // 提交之前格式化数据
  function formatData() {
    const data = cloneDeep(menuData.left);
    data.forEach((d) => {
      loopData(d);
    });
    function loopData(d) {
      if (d.type == 'view') {
        for (let j in d) {
          if (!view.includes(j)) delete d[j];
        }
      }
      if (d.type == 'miniprogram') {
        for (let j in d) {
          if (!miniprogram.includes(j)) delete d[j];
        }
      }
      if (d.type == 'click') {
        for (let j in d) {
          if (!click.includes(j)) delete d[j];
        }
        d.key = d.media_type + '|' + d.media_id;
        delete d.media_type;
        delete d.media_id;
      }
      if (d.sub_button && d.sub_button.length > 0) {
        for (let j in d) {
          if (j != 'name' && j != 'sub_button') delete d[j];
        }
        d.sub_button.forEach((s) => {
          loopData(s);
        });
      } else {
        delete d.sub_button;
      }
    }
    return data;
  }
  async function save() {
    let submitForm = { name: menuData.detail.name, rules: formatData() };
    const { error } =
      props.modal.params.type == 'add'
        ? await wechat.admin.menu.add(submitForm)
        : await wechat.admin.menu.edit(props.modal.params.id, submitForm);
    if (error == 0) {
      emit('modalCallBack', { event: 'confirm' });
    }
  }
  async function publish() {
    let submitForm = {
      name: menuData.detail.name,
      rules: formatData(),
      publish: 1,
    };
    const { error } =
      props.modal.params.type == 'add'
        ? await wechat.admin.menu.add(submitForm)
        : await wechat.admin.menu.edit(props.modal.params.id, submitForm);
    if (error == 0) {
      emit('modalCallBack', { event: 'confirm' });
    }
  }
  onMounted(() => {
    if (props.modal.params.type == 'edit') {
      getDetail();
    }
  });
</script>
<style lang="scss" scoped>
  .menu-name {
    width: 160px;
  }
  .menu-content {
    align-items: flex-start;
    // justify-content: center;
    padding: 0 0 20px 0;
    .el-row {
      width: 100%;
    }
    .menu-content-left {
      width: 100%;
      max-width: 268px;
      height: 420px;
      border: 1px solid var(--sa-border);
      margin-right: 30px;
      padding-top: 382px;
      font-size: 12px;
      position: relative;
      .title {
        position: absolute;
        top: 0;
        width: 100%;
        height: 36px;
        line-height: 36px;
        text-align: center;
        background: var(--sa-table-header-bg);
      }
      .left-bottom {
        position: relative;
        height: 36px;
        border-top: 1px solid var(--sa-border);
        .left-icon {
          width: 36px;
          justify-content: center;
        }
        .left-add {
          height: 36px;
          flex: 1;
          color: var(--sa-font);
          border-left: 1px solid var(--sa-border);
        }
        .menu-item {
          width: 100%;
          height: 36px;
          padding: 0 8px;
          border: 1px solid var(--sa-border);
          border-bottom: none;
          line-height: 36px;
          text-align: center;
          color: var(--sa-font);
          &.active {
            border: 1px solid var(--el-color-primary);
            color: var(--el-color-primary);
          }
        }
        .draggable-item {
          position: relative;
          border: none;
          border-left: 1px solid var(--sa-border);
          flex: 1;
          .menu-level2-body {
            display: none;
            position: absolute;
            bottom: 48px;
            width: calc(100% + 2px);
            .menu-level2-add {
              width: 100%;
              border: 1px solid var(--sa-border);
              position: relative;
              &::before {
                content: '';
                width: 0;
                height: 0;
                border: 8px solid;
                position: absolute;
                bottom: -16px;
                border-color: var(--sa-border) transparent transparent;
                z-index: 1;
              }
              &:after {
                content: '';
                width: 0;
                height: 0;
                border: 7px solid;
                position: absolute;
                bottom: -14px;
                left: 50%;
                margin-left: -5px;
                border-color: var(--sa-background-assist) transparent transparent;
                z-index: 2;
              }
            }
            &.menu-level2-body-show {
              display: block;
            }
          }
        }
      }
      .tip {
        text-align: center;
      }
    }
    .menu-content-right-tip {
      width: 100%;
      height: 420px;
    }
    .menu-content-right {
      width: 100%;
      max-width: 858px;
      min-height: 320px;
      padding: 20px 24px;
      border: 1px solid var(--sa-border);
      border-radius: 8px;
      background: var(--sa-table-header-bg);
      .title {
        font-size: 14px;
        color: var(--sa-title);
      }
      .delete {
        font-size: 14px;
        color: var(--el-color-danger);
        cursor: pointer;
      }
    }
    .tip {
      height: 12px;
      line-height: 12px;
      font-size: 12px;
      margin: 8px 0 0 0;
      color: var(--el-color-warning);
    }
  }
  @media only screen and (max-width: 768px) {
    .menu-content {
      flex-wrap: wrap;
      .menu-content-left {
        width: 100%;
        max-width: unset;
        margin: 0 0 48px;
      }
    }
  }

  .material-select {
    position: relative;
    .title {
      width: 100px;
      flex-shrink: 0;
    }
    .media_id {
      flex: 1;
    }
    .material-select-pagination {
      position: sticky;
      height: 32px;
      top: 0;
      z-index: 1;
      justify-content: flex-end;
    }
  }
</style>
